package com.ruoyi.common.utils.security;

import org.apache.shiro.codec.Base64;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.KeyGenerator;

/**
 * 对称密钥密码算法工具类
 *
 * @author ruoyi
 */
public class CipherUtils
{
    /**
     * 生成随机秘钥
     *
     * @param keyBitSize 字节大小
     * @param algorithmName 算法名称
     * @return 创建密匙
     */
    public static Key generateNewKey(int keyBitSize, String algorithmName)
    {
        KeyGenerator kg;
        try
        {
            kg = KeyGenerator.getInstance(algorithmName);
        }
        catch (NoSuchAlgorithmException e)
        {
            String msg = "Unable to acquire " + algorithmName + " algorithm.  This is required to function.";
            throw new IllegalStateException(msg, e);
        }
        kg.init(keyBitSize);
        System.out.println("key-------" + kg.generateKey().toString());
        return kg.generateKey();
    }

    protected void genKey() {
        // 生成128位的AES密钥
        Key key = CipherUtils.generateNewKey(128, "AES");

        // 获取密钥的字节数组
        byte[] keyBytes = key.getEncoded();

        // 将字节数组编码为Base64字符串
        String base64Key = Base64.encodeToString(keyBytes);

        // 输出Base64编码的密钥字符串
        System.out.println("Base64 Encoded Cipher Key: " + base64Key);

    }

    public static void main(String[] args) {
        new CipherUtils().genKey();
    }
}
